import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
//使用路由插件
Vue.use(VueRouter);
/* 
  为什么要重写push,因为push方法返回promise实例,但是如果我们不传递第三个参数onAbort,则push内部的catch函数没有处理异常的回调函数,所以如果push出错,就会直接抛出错误到浏览器上
*/

//重写路由push方法
const lastPush = VueRouter.prototype.push;
/*
push在VueRouter的原型上放,直接修改为新的函数并传递三个参数,传入的onComplate和onAbort参数的默认参数为一个函数 这样当有报错的时候 catch就会有回调函数进行处理(关键)
*/
VueRouter.prototype.push = function (
  location,
  onComplete = () => {},
  onAbort = () => {}
) {
  /* 
    因为之前的push在VueRouter的原型对象上放,所以原本的push中this就是指向VueRouter的实例
    但是现在lastPush被直接默认调用,所以this就指向了undefined了,内部很可能出错
    我们在调用lastPush的时候,可以改变他的this指向VueRouter的实例
  */
  return lastPush.call(this, location, onComplete, onAbort);
};

//引入路由组件(懒加载)
const Home = () => import("@pages/Home/Home.vue");
const Login = () => import("@pages/Login/Login.vue");
const Search = () => import("@pages/Search/Search.vue");
const Register = () => import("@pages/Register/Register.vue");
const Detail = () => import("@pages/Detail/Detail.vue");
const AddCartSuccess = () => import("@pages/AddCartSuccess/AddCartSuccess.vue");
const ShopCart = () => import("@/pages/ShopCart/ShopCart.vue");
const Pay = () => import("@pages/Pay/Pay.vue");
const PaySuccess = () => import("@pages/PaySuccess/PaySuccess.vue");
const Center = () => import("@pages/Center/Center.vue");
const Trade = () => import("@pages/Trade/Trade.vue");
const MyCenter = () => import("@pages/Center/MyCenter/MyCenter.vue");
const TeamCenter = () => import("@/pages/Center/TeamCenter/TeamCenter.vue");
const router = new VueRouter({
  // 路由滚动行为
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
  mode: "history",
  routes: [
    // 默认路由
    {
      path: "/",
      redirect: "/home",
    },
    {
      path: "/home",
      component: Home,
      name: "home",
    },
    {
      path: "/search/:keyword?",
      component: Search,
      name: "search",
    },
    {
      path: "/login",
      component: Login,
      name: "login",
      meta: {
        FooterIsHidden: true,
      },
      //路由独享守卫控制login的路由权限
      /* 
        需求：我们希望用户登录后不在有login的权限 只有在退出登陆后才可以重新访问login
      */
      beforeEnter(to, from, next) {
        const token = store.state.user.token;
        //我们用token去判断用户是否处于登录状态
        if (token) {
          next("/");
        } else {
          next();
        }
      },
    },
    {
      path: "/register",
      component: Register,
      name: "register",
      meta: {
        FooterIsHidden: true,
      },
    },
    {
      path: "/detail/:skuId",
      component: Detail,
      name: "detail",
    },
    {
      path: "/addCartSuccess",
      component: AddCartSuccess,
      name: "addCartSuccess",
      beforeEnter(to, from, next) {
        //判断用户是否从添加购物车详情页过来 如果不是 则让他返回到home页
        if (sessionStorage.getItem("cartData")) {
          next();
        } else {
          next("/home");
        }
      },
    },
    {
      path: "/shopCart",
      component: ShopCart,
      name: "shopCart",
    },
    {
      path: "/center",
      component: Center,
      //name: "center",
      children: [
        {
          path: "mycenter",
          component: MyCenter,
          name: "mycenter",
        },
        {
          path: "teamcenter",
          component: TeamCenter,
          name: "teamcenter",
        },
        //默认子路由
        {
          path: "",
          redirect: "/center/mycenter",
        },
      ],
    },
    {
      path: "/pay",
      component: Pay,
      name: "pay",
      //用户只能从tarde页面进入到pay
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/trade")) {
          next();
        } else {
          //如果不是则让他回到主页
          next("/home");
        }
      },
    },
    {
      path: "/paySuccess",
      component: PaySuccess,
      name: "paySuccess",
      //用户只能从pay进入到paySuccess
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/pay")) {
          next();
        } else {
          next("/home");
        }
      },
    },
    {
      path: "/trade",
      component: Trade,
      name: "trade",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/shopcart")) {
          next();
        } else {
          next("/home");
        }
      },
    },
  ],
});

//全局前置守卫
router.beforeEach((to, from, next) => {
  //定义一个数组用来保存需要token才可以访问的路由组件
  const checkPath = ["/center", "/pay", "/paysuccess", "/trade", "/shopCart"];
  //数组的some的方法  有一个满足结果为ture 所有都不满足为false
  const isCkeckPath = checkPath.some((item) => {
    // 考虑多级路由的原因 我们使用startWith方法  判断是否包含这个字符串(以item开头) 返回值为布尔值
    return to.path.startsWith(item);
  });
  //获取到vuex中token和nickName
  const token = store.state.user.token;
  const nickName = store.state.user.nickName;
  //判断用户名是否存在  如果存在则证明用户已经是登录状态 放行
  if (nickName) {
    next();
  }
  if (isCkeckPath) {
    //进入这个判断 我们需要token权限校验
    if (token) {
      //如果有token则证明用户已经登录了,我们只需要发送请求获取下用户名
      store.dispatch("user/getUserInfo");
      //放行
      next();
    } else {
      //表示用户并没有登录我们让他直接返回到登录页面
      alert("请登录");
      next("/login");
    }
  } else {
    //进入这里的判断则证明当前路由并不需要token的权限校验 但是如果有token的话也顺便请求一下用户信息
    if (token) {
      store.dispatch("user/getUserInfo");
    }

    next();
  }
});

export default router;
